package store.swing.order;

import store.domain.Order;
import store.domain.OrderStatus;
import store.util.AppUtils;

import javax.swing.table.AbstractTableModel;
import java.util.List;

public class OrderTableModel extends AbstractTableModel {
    private static final String[] COLUMN_NAMES = {"ID", "Номер заказа", "Имя клиента", "Телефон", "E-mail", "Статус заказа", "Сумма"};
    private static List<Order> orders = AppUtils.getService("orderService").readAll();
    private static List<OrderStatus> orderStatuses = AppUtils.getService("orderStatusService").readAll();

    @Override
    public int getRowCount() {
        return orders.size();
    }

    @Override
    public int getColumnCount() {
        return COLUMN_NAMES.length;
    }

    @Override
    public String getColumnName(int column) {
        return COLUMN_NAMES[column];
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        switch (columnIndex) {
            case 0:
                return orders.get(rowIndex).getOrderId();
            case 1:
                return orders.get(rowIndex).getOrderNumber();
            case 2:
                return orders.get(rowIndex).getfName() + " " + orders.get(rowIndex).getlName();
            case 3:
                return orders.get(rowIndex).getPhone();
            case 4:
                return orders.get(rowIndex).getEmail();
            case 5:
                return getOrderStatusName(rowIndex);
            case 6:
                return orders.get(rowIndex).getOrderTotal();
        }
        return null;
    }

    public static List<Order> getOrders() {
        return orders;
    }

    public static void setOrders(List<Order> orders) {
        OrderTableModel.orders = orders;
    }

    public static List<OrderStatus> getOrderStatuses() {
        return orderStatuses;
    }

    private String getOrderStatusName(int rowIndex){
        Integer statusId = Integer.valueOf(orders.get(rowIndex).getOrderStatus());
        String orderStatusName = "";
        for (OrderStatus orderStatus : orderStatuses) {
            if (orderStatus.getStatusId().equals(statusId)) {
                orderStatusName = orderStatus.getNameRuRu();
                break;
            }
        }
        return orderStatusName;
    }
}
